package com.example.hrsystem.ui.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.TaskItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务列表界面Activity
 * 显示待办/待阅事项列表
 */
public class TaskListActivity extends AppCompatActivity {

    private TaskViewModel taskViewModel;
    private RecyclerView taskRecyclerView;
    private TaskListAdapter taskAdapter;
    private List<TaskItem> taskList = new ArrayList<>();
    private TextView todoCountTextView;
    private TextView readCountTextView;
    private TextView doneCountTextView;
    private TextView readDoneCountTextView;
    private FloatingActionButton addTaskButton;
    private String currentTaskType = "全部";
    private String currentStatus = "全部";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);

        // 初始化UI组件
        initUI();

        // 初始化ViewModel
        taskViewModel = new ViewModelProvider(this).get(TaskViewModel.class);

        // 观察加载状态
        taskViewModel.getIsLoading().observe(this, isLoading -> {
            // 可以在这里显示加载指示器
        });

        // 观察错误信息
        taskViewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察任务列表
        observeTasks();

        // 观察任务统计数据
        observeTaskStatistics();

        // 设置添加任务按钮点击事件
        addTaskButton.setOnClickListener(v -> {
            // 这里应该跳转到创建任务的界面
            Toast.makeText(this, "创建新任务功能待实现", Toast.LENGTH_SHORT).show();
        });
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        taskRecyclerView = findViewById(R.id.task_recycler_view);
        todoCountTextView = findViewById(R.id.todo_count_text_view);
        readCountTextView = findViewById(R.id.read_count_text_view);
        doneCountTextView = findViewById(R.id.done_count_text_view);
        readDoneCountTextView = findViewById(R.id.read_done_count_text_view);
        addTaskButton = findViewById(R.id.add_task_button);

        // 初始化RecyclerView
        taskAdapter = new TaskListAdapter(taskList, this::onTaskItemClick);
        taskRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        taskRecyclerView.setAdapter(taskAdapter);

        // 设置分类标签点击事件
        findViewById(R.id.all_tasks_tab).setOnClickListener(v -> filterTasks("全部", currentStatus));
        findViewById(R.id.todo_tasks_tab).setOnClickListener(v -> filterTasks("待办", currentStatus));
        findViewById(R.id.read_tasks_tab).setOnClickListener(v -> filterTasks("待阅", currentStatus));
        findViewById(R.id.unstarted_tasks_tab).setOnClickListener(v -> filterTasks(currentTaskType, "未开始"));
        findViewById(R.id.in_progress_tasks_tab).setOnClickListener(v -> filterTasks(currentTaskType, "进行中"));
        findViewById(R.id.completed_tasks_tab).setOnClickListener(v -> filterTasks(currentTaskType, "已完成"));
    }

    /**
     * 观察任务列表
     */
    private void observeTasks() {
        // 观察所有任务
        taskViewModel.getAllTasks().observe(this, tasks -> {
            updateTaskList(tasks);
        });
    }

    /**
     * 观察任务统计数据
     */
    private void observeTaskStatistics() {
        // 观察待办事项总数
        taskViewModel.getTodoTaskCount("1001").observe(this, count -> {
            todoCountTextView.setText("待办事项：" + count);
        });

        // 观察待阅事项总数
        taskViewModel.getReadTaskCount("1001").observe(this, count -> {
            readCountTextView.setText("待阅事项：" + count);
        });

        // 观察已办事项总数
        taskViewModel.getDoneTaskCount("1001").observe(this, count -> {
            doneCountTextView.setText("已办事项：" + count);
        });

        // 观察已阅事项总数
        taskViewModel.getReadDoneTaskCount("1001").observe(this, count -> {
            readDoneCountTextView.setText("已阅事项：" + count);
        });
    }

    /**
     * 更新任务列表
     */
    private void updateTaskList(List<TaskItem> tasks) {
        taskList.clear();
        taskList.addAll(tasks);
        taskAdapter.notifyDataSetChanged();
    }

    /**
     * 筛选任务
     */
    private void filterTasks(String taskType, String status) {
        currentTaskType = taskType;
        currentStatus = status;

        if ("全部".equals(taskType) && "全部".equals(status)) {
            taskViewModel.getAllTasks().observe(this, tasks -> {
                updateTaskList(tasks);
            });
        } else if ("全部".equals(taskType)) {
            taskViewModel.getTasksByStatus(status).observe(this, tasks -> {
                updateTaskList(tasks);
            });
        } else if ("全部".equals(status)) {
            taskViewModel.getTasksByType(taskType).observe(this, tasks -> {
                updateTaskList(tasks);
            });
        } else {
            // 实现同时按类型和状态筛选的逻辑
            taskViewModel.getAllTasks().observe(this, allTasks -> {
                List<TaskItem> filteredTasks = new ArrayList<>();
                for (TaskItem task : allTasks) {
                    if (taskType.equals(task.getTaskType()) && status.equals(task.getStatus())) {
                        filteredTasks.add(task);
                    }
                }
                updateTaskList(filteredTasks);
            });
        }
    }

    /**
     * 任务项点击事件处理
     */
    private void onTaskItemClick(TaskItem task) {
        // 跳转到任务详情界面
        Intent intent = new Intent(this, TaskDetailActivity.class);
        intent.putExtra("taskId", task.getId());
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新任务列表
        filterTasks(currentTaskType, currentStatus);
    }
}